<template>
  <page-header-wrapper
    :title="pipeline.name"
    :sub-title="pipeline.description"
    :tab-list="tabList"
    :tab-active-key="tabActiveKey"
    @tabChange="handleTabChange"
  >
    <template slot="tags">
      <Tag v-if="pipeline.status != 3" :color="statusColorMap[pipeline.status]">{{statusNameMap[pipeline.status]}}</Tag>
      <Tag v-if="pipeline.status == 3" :color="statusColorMap[pipeline.status]"><a >{{statusNameMap[pipeline.status]}} <a-icon type="alert" /> </a></Tag>
    </template>
    <template v-slot:content>
      <a-descriptions size="small">
        <a-descriptions-item label="workers">{{pipeline.workers}}</a-descriptions-item>
        <a-descriptions-item label="batch size">{{pipeline.batchSize}}</a-descriptions-item>
        <a-descriptions-item label="batch delay">{{pipeline.batchDelay}}</a-descriptions-item>
        <a-descriptions-item label="queue type">{{pipeline.queueType}}</a-descriptions-item>
        <a-descriptions-item label="queue max bytes">{{pipeline.queueMaxBytes}}</a-descriptions-item>
        <a-descriptions-item label="queue checkpoint">{{pipeline.queueCheckpointWrites}}</a-descriptions-item>
        <a-descriptions-item label="run host">{{pipeline.actualRunHost}}</a-descriptions-item>
      </a-descriptions>
      <div style="color:red" v-show="pipeline.log">error log: <span v-text="pipeline.log"></span></div>
    </template>

    <!-- actions -->
    <template v-slot:extra>
      <a-button-group style="margin-right: 4px;">
        <a-button @click="$router.go(-1)">返回</a-button>
        <a-button @click="toEditPipeline">编辑</a-button>
        <a-button @click="restart">重启</a-button>
      </a-button-group>
    </template>

    <a-row  v-show="tabActiveKey == 'detail'">
      <a-col :span="12" style="padding: 10px">
        <div style="width: 100%;height: 350px;"  id="memChartDiv" class="showDiv">

        </div>
      </a-col>
      <a-col :span="12" style="padding: 10px">
        <div style="width: 100%;height: 350px;"  id="eventsChartDiv" class="showDiv">

        </div>
      </a-col>
    </a-row>
    <a-row  v-show="tabActiveKey == 'detail'">
      <a-col :span="12" style="padding: 10px">
        <div style="width: 100%;height: 350px;"  id="threadChartDiv" class="showDiv">

        </div>
      </a-col>
      <a-col :span="12" style="padding: 10px">
        <div style="width: 100%;height: 350px;"  id="cpuChartDiv" class="showDiv">

        </div>
      </a-col>
    </a-row>

    <a-card v-show="tabActiveKey == 'log'" style="margin-top: 24px" :bordered="false" title="用户信息">
      <pipeline-log :pipeline-id="pipeline.id"></pipeline-log>
    </a-card>
    <a-card v-show="tabActiveKey == 'codes'" style="margin-top: 24px" :bordered="false">
      <div class="codeDiv">
        <codemirror v-model="codes" :options="codeOptions" style="min-height: 500px"></codemirror>
        <div class="versionDiv">
          <a-button style="margin-left: 8px" type="primary" v-text="'version: ' + pipeline.runCodeVersion"></a-button>
        </div>
      </div>
    </a-card>
    <!-- 操作 -->

  </page-header-wrapper>
</template>

<script>
  import { baseMixin } from '@/store/app-mixin'
  import { getPipeline } from '@/api/logstash_pipeline'
  import { Collapse, Tag } from 'ant-design-vue'
  import {codemirror} from 'vue-codemirror'
  import 'codemirror/lib/codemirror.css'
  // 引入主题,配置后生效
  import 'codemirror/theme/idea.css'
  //引入语言,配置后生效
  import 'codemirror/mode/puppet/puppet.js'
  import LogstashPipelineLog from './LogstashPipelineLog'
  import { staPipelineInfo } from '@/api/logstash_monitor'
  import { restartPipeline } from '@/api/logstash_pipeline'

  import echarts from '@/components/echarts'

  export default {
    name: 'Advanced',
    mixins: [baseMixin],
    components: {
      Tag,
      codemirror,
      'pipeline-log': LogstashPipelineLog
    },
    data () {
      return {
        pipelineId: null,
        pipeline: {},
        statusNameMap: {0: "未运行", 1: "调度中", 2: "运行中", 3: "运行错误"},
        statusColorMap: {0: "volcano", 1: "lime", 2: "green", 3: "red"},
        tabList: [
          { key: 'detail', tab: '运行情况' },
          { key: 'log', tab: '日志' },
          { key: 'codes', tab: '脚本' },
        ],
        tabActiveKey: 'detail',
        codeOptions: {
          tabSize: 2, // 缩进格式
          theme: 'idea', // 指定主题，对应主题库 JS 需要提前引入
          lineNumbers: true, // 是否显示行号
          //指定语言类型,如果需要编辑和显示其他语言,需要import语言js然后修改此配置
          mode: 'puppet',
          line: true,
          styleActiveLine: true, // 高亮选中行
          hintOptions: {
            completeSingle: true // 当匹配只有一项的时候是否自动补全
          },
          readOnly: true
        },
        codes: "",
        queryMonitor: {
          timeType: 1,
          pipelineId: null
        },
        memOptions: null,
        memChart: null,
        eventsChart: null,
        eventsOptions: null,
        intervalSta: null
      }
    },
    filters: {
      statusFilter (status) {
        const statusMap = {
          'agree': '成功',
          'reject': '驳回'
        }
        return statusMap[status]
      },
      statusTypeFilter (type) {
        const statusTypeMap = {
          'agree': 'success',
          'reject': 'error'
        }
        return statusTypeMap[type]
      }
    },
    methods: {
      getPipeline (id) {
        getPipeline(id).then(res => {
          if(res.code == 200){
            if(res.data){
              this.pipeline = res.data
              this.codes = res.pipelineCodes
            }
          }
        })
      },
      handleTabChange (key) {
        console.log('')
        this.tabActiveKey = key
        if(key == 'codes'){
          this.codes = this.codes + ' '
        }
      },
      staPipelineInfo () {
        staPipelineInfo(this.queryMonitor.timeType, this.queryMonitor.pipelineId).then(res => {
          if(res.code == 200 && res.data){
            let useMem = []
            let times = []
            let inData = []
            let outData = []
            let filterData = []
            let threadData = []
            let cpuData = []
            let lastIn = 0
            let lastOut = 0
            let lastFilter = 0
            for (let i = 0; i < res.data.length; i++) {
              let row = res.data[i]
              useMem.push(row.use_memery)
              times.push(row.time_format)
              threadData.push(row.threads_count)
              cpuData.push(row.use_cpu_percent)

              if(i != 0){
                inData.push(row.events_in - lastIn)
                outData.push(row.events_out - lastOut)
                filterData.push(row.events_filtered - lastFilter)
              }
              lastIn = row.events_in
              lastOut = row.events_out
              lastFilter = row.events_filtered
            }
            this.loadMemChart(times, useMem)
            this.loadEventsChart(times.filter((v, i) => i != 0), inData, outData, filterData)
            this.eventsChart.hideLoading()
            this.loadCpuChart(times, cpuData)
            this.loadThreadChart(times, threadData)
          }
        })
      },
      loadMemChart(xAxisData, data){
        if(this.memChart == null){
          this.memChart = echarts.init(document.getElementById('memChartDiv'));
          this.memOptions = {
            title: {
              text: 'memory used'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                formatter: '{value}M'
              }
            },
            series: [
              {
                data: [],
                type: 'line',
                smooth: true
              }
            ]
          }
          this.memChart.showLoading()
        }
        this.memOptions.xAxis.data = xAxisData;
        this.memOptions.series[0].data = data;
        this.memChart.setOption(this.memOptions);
        if(data.length > 0){
          this.memChart.hideLoading()
        }
      },
      loadCpuChart(xAxisData, data){
        if(this.cpuChart == null){
          this.cpuChart = echarts.init(document.getElementById('cpuChartDiv'));
          this.cpuOptions = {
            title: {
              text: 'cpu used percent'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: [],
                type: 'line',
                smooth: true
              }
            ]
          }
          this.cpuChart.showLoading()
        }
        this.cpuOptions.xAxis.data = xAxisData;
        this.cpuOptions.series[0].data = data;
        this.cpuChart.setOption(this.cpuOptions);
        if(data.length > 0){
          this.cpuChart.hideLoading()
        }
      },
      loadThreadChart(xAxisData, data){
        if(this.threadChart == null){
          this.threadChart = echarts.init(document.getElementById('threadChartDiv'));
          this.threadOptions = {
            title: {
              text: 'threads'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: [],
                type: 'line',
                smooth: true
              }
            ]
          }
          this.threadChart.showLoading()
        }
        this.threadOptions.xAxis.data = xAxisData;
        this.threadOptions.series[0].data = data;
        this.threadChart.setOption(this.threadOptions);
        if(data.length > 0){
          this.threadChart.hideLoading()
        }
      },
      loadEventsChart(xAxisData, inData, outData, filterData){
        if(this.eventsChart == null){
          this.eventsChart = echarts.init(document.getElementById('eventsChartDiv'));
          this.eventsOptions = {
            title: {
              text: 'events'
            },
            tooltip: {
              trigger: 'axis'
            },
            xAxis: {
              type: 'category',
              data: []
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: "in",
                data: [],
                type: 'bar',
              },
              {
                name: "out",
                data: [],
                type: 'bar',
              },
              {
                name: "filter",
                data: [],
                type: 'bar',
              },
            ]
          }
          this.eventsChart.showLoading()
        }
        this.eventsOptions.xAxis.data = xAxisData;
        this.eventsOptions.series[0].data = inData;
        this.eventsOptions.series[1].data = outData;
        this.eventsOptions.series[2].data = filterData;
        this.eventsChart.setOption(this.eventsOptions);
        if(xAxisData.length > 0){
          this.eventsChart.hideLoading()
        }
      },
      toEditPipeline () {
        this.$router.push({ path: '/pipeline/edit', query: {id: this.pipelineId} })
      },
      restart(){
        let me = this
        if(this.pipelineId){
          this.$confirm({
            title: '提示',
            content: `确认重启该管道吗？`,
            okText: '重启',
            okType: 'danger',
            cancelText: '取消',
            onOk () {
              restartPipeline(me.pipelineId).then(res => {
                if(res.code == 200){
                  me.getPipeline(me.pipelineId)
                }else{
                  me.$message.error(res.msg)
                }
              })
            },
            onCancel () {
            }
          })
        }
      }
    },
    created () {

    },
    mounted() {
      this.pipelineId = this.$route.query.id
      this.loadMemChart([], [])
      this.loadEventsChart([], [], [], [])
      this.loadThreadChart([], [])
      this.loadCpuChart([], [])
      if(this.pipelineId){
        this.getPipeline(this.pipelineId)
        this.queryMonitor.pipelineId = this.$route.query.id

        this.staPipelineInfo()
        this.intervalSta = setInterval(() => {
          this.staPipelineInfo()
          this.getPipeline(this.pipelineId)
        }, 1000 * 30);
      }
    },
    destroyed () {
      clearInterval(this.intervalSta)
    }

  }
</script>
<style>
  .codeDiv {
    border: solid 2px #f0f2f5;
  }
  .CodeMirror {
    overscroll-y: scroll !important;
    height: 700px !important;
  }
  .versionDiv {
    position: absolute;
    top: 24px;
    right: 24px;
    z-index: 99999999;
  }
  .showDiv{
    background:#fff;
    color:#333;
    box-shadow: 2px 2px 10px #3f80a5;
  }
</style>